package com.hifar.demo;

import javax.xml.transform.*;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.*;
import java.io.*;

public class S1000DToPdfConverter {

    public static void main(String[] args) {
        try {
            // 输入输出文件路径
            File xmlFile = new File("src/main/resources/data/11.xml");
            File xsltFile = new File("src/main/resources/templates/s1000d-to-fo.xsl");
            File pdfFile = new File("output/11.pdf");

            // 转换XML到PDF
            convertToPDF(xmlFile, xsltFile, pdfFile);

            System.out.println("PDF生成成功: " + pdfFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void convertToPDF(File xmlFile, File xsltFile, File pdfFile)
            throws IOException, FOPException, TransformerException {

        // 修复 fopFactory 作用域问题，将其定义移到 try-catch 外部
        FopFactory fopFactory;
        try {
            fopFactory = FopFactory.newInstance(new File("src/main/resources/templates/fop.conf"));
            // FopFactory 没有 getValidationSettings() 方法，使用 setStrictValidation 替代方案
            // 通过 FOUserAgent 设置验证级别
            // 将 FOUserAgent 的创建和设置验证级别移到 try-catch 块内，确保在 fopFactory 创建后执行
        } catch (org.xml.sax.SAXException e) {
            throw new RuntimeException(" 初始化FopFactory时发生SAXException", e);
        }
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();

        // 设置输出流
        OutputStream out = new BufferedOutputStream(new FileOutputStream(pdfFile));

        try {
            // 初始化FOP
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

            // 设置XSLT转换器，并指定编码
            // 在convertToWord方法中添加XML声明
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(new StreamSource(xsltFile));
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

            Source src = new StreamSource(new InputStreamReader(
                    new FileInputStream(xmlFile), "UTF-8"));
            // Source src = new StreamSource(reader);

            // 执行转换
            Result res = new SAXResult(fop.getDefaultHandler());
            transformer.transform(src, res);

        } finally {
            out.close();
        }
    }
}
